package com.guigu.yh.springcloud.loadbalance;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 我实现的负载平衡
 *
 * @author 张颖辉（zyh）
 * @version 1.0.0
 * @date 2022/08/21
 */
@Slf4j
@Component
public class MyLoadBalance implements ILoadBalance {

    private final AtomicInteger reqNo = new AtomicInteger(0);

    /**
     * 选择服务实例
     *
     * @param instances 实例
     * @return {@link ServiceInstance }
     * @author 张颖辉（zyh）
     * @date 2022/08/21
     * @version 1.0.0
     */
    @Override
    public ServiceInstance chooseServiceInstance(List<ServiceInstance> instances) {
        if (instances == null || instances.isEmpty()) {
            throw new RuntimeException("没有服务实例，无法负载均衡");
        }
        int nextReqNo = getNextReqNo();
        int index = nextReqNo % instances.size();
        return instances.get(index);
    }

    /**
     * 得到下一个请求编号
     *
     * @return int
     * @author 张颖辉（zyh）
     * @date 2022/08/21
     * @version 1.0.0
     */
    private int getNextReqNo() {
        int current;
        int next;
        do {
            current = reqNo.intValue();
            next = current >= Integer.MAX_VALUE ? 1 : current + 1;
        } while (!reqNo.compareAndSet(current, next));
        log.debug("****第{}次访问此接口 ", next);
        return next;
    }
}
